package cn.minimelon.api.config.handle;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.Context;
import org.noear.solon.data.cache.CacheService;
import org.noear.solon.validation.annotation.NoRepeatSubmit;
import org.noear.solon.validation.annotation.NoRepeatSubmitChecker;

/**
 * 重复提交验证，分布式使用Redis，单机CacheService
 */
@Slf4j
@Component
public class NoRepeatCheckerHandle implements NoRepeatSubmitChecker {

    @Inject
    CacheService cacheService;

    @Override
    public boolean check(NoRepeatSubmit submit, Context ctx, String submitHash, int limitSeconds) {
        // return redisClient.getLock("NoRepeat@" + submitHash).tryLock(limitSeconds);
        String key = "NoRepeat@" + submitHash;
        log.info("check hash:{}", submitHash);
        String obj = cacheService.get(key, String.class);
        if (StrUtil.isEmpty(obj)) {
            return true;
        } else {
            cacheService.store(key, "_", limitSeconds);
            return false;
        }
    }
}
